package ru.hh.school;

import ru.hh.school.commands.ChatRouter;
import ru.hh.school.exceptions.InnerChatException;
import ru.hh.school.logging.StaticLogger;
import ru.hh.school.persistence.DataRepository;

import java.io.IOException;
import java.io.ObjectOutputStream;

import static ru.hh.school.Constants.SUPER_QUEUE_MAX_SIZE;

public class UserOutput implements Runnable {
    private ObjectOutputStream stream;
    private SuperBlockingQueue messages;
    private ChatRouter router;
    private User user;

    public UserOutput(ObjectOutputStream stream, User user, DataRepository dataRepository, ChatRouter router) throws IOException {
        messages = new SuperBlockingQueue(SUPER_QUEUE_MAX_SIZE, user.getId(), dataRepository);
        this.stream = stream;
        this.router = router;
        this.user = user;
    }

    public void add(String message) {
        messages.add(message);
    }

    public void addSure(PrivateMessage message) {
        messages.addSure(message);
    }


    public void run() {
        try {
            try {
                while (!Thread.interrupted()) {
                    stream.writeObject(messages.take());
                    stream.flush();
                }
            } catch (InnerChatException e) {
                router.command(user, "/quit Disconnected");
            } catch (IOException e) {
                router.command(user, "/quit Disconnected");
            }
        } catch (InterruptedException e) {
            StaticLogger.getLogger().logError(e);
        } finally {
            try {
                stream.close();
            } catch (IOException e) {
                StaticLogger.getLogger().logError(e);
            }
        }

    }

}
